// 工程化
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
// 引入路由映射组件
const router = new VueRouter({
    routes: [{
        // 默认重定向
        path: '/',
        redirect: { name: 'index' }
    },
    {
        name: 'index',
        path: '/index',
        component: () => import('@/views/index.vue')
    },
    {
        name: 'articaldetail',
        path: '/articaldetail/:id',
        component: () => import('@/views/articaldetail.vue')
    },
    {
        name: 'login',
        path: '/login',
        component: () => import('@/views/login.vue')
    }, {
        name: 'personal',
        path: '/personal/:id',
        component: () => import('@/views/personal.vue')
    },
    {
        name: 'edit_profile',
        path: '/edit_profile/:id',
        component: () => import('@/views/edit_profile.vue')
    },
    {
        name: 'userStars',
        path: '/userStars/:id',
        component: () => import('@/views/userStars.vue')
    },
    {
        name: 'userFollow',
        path: '/userFollow/:id',
        component: () => import('@/views/userFollow.vue')
    },
    {
        name: 'commentList',
        path: '/commentList/:id',
        component: () => import('@/views/commentList.vue')
    },
    {
        name: 'categoryMannager',
        path: '/categoryMannager',
        component: () => import('@/views/categoryMannager.vue')
    },
    ]
})
const url = ['personal', 'edit_profile']
// 导航守卫，没有tokende返回login页面
router.beforeEach((to, from, next) => {
    url.forEach((item) => {
        // console.log(to);
        if (to.name == item) {
            // 当有这个路由需要token，我们先需要验证本地存储有没有token值
            // console.log(1);
            // if (JSON.parse(window.localStorage.getItem('toutiao')).data.token) {
            if (window.localStorage.getItem('toutiao_token')) {
                next()  //必写 ，
            } else {
                next({ name: 'login' })  //必写 ，一定要调用该方法来 resolve 这个钩子。
            }
        } else {
            // 确保 next 函数在任何给定的导航守卫中都被严格调用一次。它可以出现多于一次，但是只能在所有的逻辑路径都不重叠的情况下，否则钩子永远都不会被解析或报错。
            // this.$router.push('/login')
            next()
        }
    })
})
// 解决当路由没有参数跳转的时候，或者参数有问题的时候，catch掉错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => console.dir(err))
}
// 暴露s
export default router